<!-- 角色管理 -->
<script setup lang="tsx">
import { reactive, ref, unref, watch } from 'vue'
import { sysRolePageDataList, sysRoleSaveOrUpdate, sysRoleDeleteById } from '@/api/backstage'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { Write, Detail, WriteMenu, WriteUser } from './components'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await sysRolePageDataList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.records || [],
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await sysRoleDeleteById({ id: unref(delId) })
    return !!res
  }
})

const { dataList, pageSize, currentPage, loading, total } = tableState
const { getList, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('role.roleName')
  },
  {
    field: 'roleType',
    label: '角色类型'
  },
  {
    field: 'coment',
    label: '描述信息'
  },
  {
    field: 'sortOrder',
    label: '显示排序'
  },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime')
  },
  {
    field: 'updateTime',
    label: '更新时间'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 300,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="success" link onClick={() => action(row, '详情')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="primary" link onClick={() => action(row, '设置菜单')}>
              设置菜单
            </BaseButton>
            <BaseButton type="primary" link onClick={() => action(row, '设置用户')}>
              设置用户
            </BaseButton>
            <BaseButton type="primary" link onClick={() => action(row, '编辑')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="danger" link onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'roleName',
    label: t('role.roleName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  currentPage.value = 1
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const dialogWidth = ref('50%')
const dialogHeight = ref('400px')

const currentRow = ref()
const actionType = ref('')
watch(
  () => actionType.value,
  (val) => {
    console.log('actionType', val)
    switch (val) {
      case '新增':
        dialogWidth.value = '50%'
        dialogHeight.value = '200px'
        break
      case '编辑':
        dialogWidth.value = '50%'
        dialogHeight.value = '200px'
        break
      case '详情':
        dialogWidth.value = '50%'
        dialogHeight.value = '600px'
        break
      case '设置菜单':
        dialogWidth.value = '80%'
        dialogHeight.value = '600px'
        break
      case '设置用户':
        dialogWidth.value = '80%'
        dialogHeight.value = '600px'
        break
    }
  }
)

const writeRef = ref<ComponentRef<typeof Write>>()
const WriteMenuRef = ref<ComponentRef<typeof WriteMenu>>()
const WriteUserRef = ref<ComponentRef<typeof WriteUser>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = type
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = '新增'
  dialogHeight.value = '200px'
}

const delLoading = ref(false)
const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    try {
      console.log('保存提交', formData)

      const res = await sysRoleSaveOrUpdate(formData)
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

/** 设置菜单回调，关闭弹窗 */
const menuSave = async () => {
  saveLoading.value = true
  const ref = unref(WriteMenuRef)
  const success = await ref?.submit()
  if (success) {
    saveLoading.value = false
    dialogVisible.value = false
  } else {
    saveLoading.value = false
  }
}
const userSave = async () => {
  saveLoading.value = true
  const ref = unref(WriteUserRef)
  const success = await ref?.submit()
  if (success) {
    saveLoading.value = false
    dialogVisible.value = false
  } else {
    saveLoading.value = false
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      :operationAdd="true"
      @add="AddAction"
    />

    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="dialogWidth"
    :maxHeight="dialogHeight"
  >
    <Write v-if="['新增', '编辑'].includes(actionType)" ref="writeRef" :current-row="currentRow" />
    <Detail v-if="actionType === '详情'" :current-row="currentRow" />
    <WriteMenu v-if="actionType === '设置菜单'" ref="WriteMenuRef" :current-row="currentRow" />
    <WriteUser v-if="actionType === '设置用户'" ref="WriteUserRef" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="['新增', '编辑'].includes(actionType)"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton
        v-if="actionType === '设置菜单'"
        type="primary"
        :loading="saveLoading"
        @click="menuSave"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton
        v-if="actionType === '设置用户'"
        type="primary"
        :loading="saveLoading"
        @click="userSave"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
